<template>
  <div class="department-management">
    <div class="page-header">
      <h1>部门管理</h1>
      <a-button type="primary" @click="showAddModal">
        <template #icon>
          <PlusOutlined />
        </template>
        添加部门
      </a-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search 
            v-model:value="searchForm.name" 
            placeholder="搜索部门名称" 
            @search="handleSearch" 
          />
        </a-col>
        <a-col :span="6">
          <a-input v-model:value="searchForm.code" placeholder="部门编码" />
        </a-col>
        <a-col :span="4">
          <a-button @click="resetSearch">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 部门表格 -->
    <div class="department-table">
      <a-table 
        :columns="columns" 
        :data-source="departmentList" 
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 0 ? 'green' : 'red'">
              {{ record.status === 0 ? '审核通过' : '审核未通过' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'applyInfo'">
            <div v-if="record.remarkInfo">
              <div><strong>申请人:</strong> {{ record.remarkInfo.applicant || '未知' }}</div>
              <div><strong>申请理由:</strong> {{ record.remarkInfo.applyReason || '无' }}</div>
              <div><strong>申请时间:</strong> {{ record.remarkInfo.applyTime || '未知' }}</div>
            </div>
            <div v-else>无申请信息</div>
          </template>
          <template v-else-if="column.key === 'auditInfo'">
            <div v-if="record.remarkInfo">
              <div><strong>审核人:</strong> {{ record.remarkInfo.auditor || '未审核' }}</div>
              <div><strong>审核意见:</strong> {{ record.remarkInfo.auditReason || '无' }}</div>
              <div><strong>审核时间:</strong> {{ record.remarkInfo.auditTime || '未审核' }}</div>
            </div>
            <div v-else>未审核</div>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="editDepartment(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除这个部门吗？"
                @confirm="deleteDepartment(record.id)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑部门弹窗 -->
    <a-modal 
      v-model:open="modalVisible" 
      :title="isEditing ? '编辑部门' : '添加部门'" 
      width="800px" 
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitting"
    >
      <a-form 
        ref="formRef" 
        :model="departmentForm" 
        :rules="formRules" 
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="部门名称" name="name">
              <a-input v-model:value="departmentForm.name" placeholder="请输入部门名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="部门编码" name="code">
              <a-input v-model:value="departmentForm.code" placeholder="请输入部门编码" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系电话" name="contactPhone">
              <a-input v-model:value="departmentForm.contactPhone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="departmentForm.status" placeholder="请选择状态">
                <a-select-option :value="0">正常</a-select-option>
                <a-select-option :value="1">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="地址" name="address">
          <a-input v-model:value="departmentForm.address" placeholder="请输入地址" />
        </a-form-item>

        <a-form-item label="营业执照" name="businessLicense">
          <a-input v-model:value="departmentForm.businessLicense" placeholder="请输入营业执照" />
        </a-form-item>

        <!-- 申请信息 -->
        <a-divider>申请信息</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请人">
              <a-input v-model:value="departmentForm.remarkInfo.applicant" placeholder="请输入申请人" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请时间">
              <a-input v-model:value="departmentForm.remarkInfo.applyTime" placeholder="请输入申请时间" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="申请理由">
          <a-textarea 
            v-model:value="departmentForm.remarkInfo.applyReason" 
            placeholder="请输入申请理由" 
            :rows="3" 
          />
        </a-form-item>

        <!-- 审核信息 -->
        <a-divider>审核信息</a-divider>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="审核人">
              <a-input v-model:value="departmentForm.remarkInfo.auditor" placeholder="请输入审核人" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="审核时间">
              <a-input v-model:value="departmentForm.remarkInfo.auditTime" placeholder="请输入审核时间" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="审核意见">
          <a-textarea 
            v-model:value="departmentForm.remarkInfo.auditReason" 
            placeholder="请输入审核意见" 
            :rows="3" 
          />
        </a-form-item>

        <!-- 历史记录 -->
        <a-divider v-if="departmentForm.remarkInfo.history && departmentForm.remarkInfo.history.length > 0">历史记录</a-divider>
        <div v-if="departmentForm.remarkInfo.history && departmentForm.remarkInfo.history.length > 0">
          <a-card 
            v-for="(item, index) in departmentForm.remarkInfo.history" 
            :key="index" 
            size="small" 
            :title="`记录 ${index + 1}`"
            style="margin-bottom: 10px;"
          >
            <p><strong>操作:</strong> {{ item.reason }}</p>
            <p><strong>操作人:</strong> {{ item.operator }}</p>
            <p><strong>时间:</strong> {{ item.time }}</p>
          </a-card>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
  queryDeptPage,
  addDept,
  updateDept,
  deleteDept
} from '@/api/user/deptController'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const modalVisible = ref(false)
const isEditing = ref(false)
const formRef = ref()

// 表单数据
const departmentForm = reactive({
  id: undefined,
  name: '',
  code: '',
  contactPhone: '',
  address: '',
  businessLicense: '',
  status: 0,
  remarkInfo: {
    applyReason: '',
    auditReason: '',
    applicant: '',
    auditor: '',
    applyTime: '',
    auditTime: '',
    history: []
  }
})

const searchForm = reactive({
  name: '',
  code: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入部门名称' }]
}

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  {
    title: '部门名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '部门编码',
    dataIndex: 'code',
    key: 'code',
    width: 120
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
    width: 120
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    width: 150
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '申请信息',
    key: 'applyInfo',
    width: 200
  },
  {
    title: '审核信息',
    key: 'auditInfo',
    width: 200
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 部门列表数据
const departmentList = ref([])

// 方法
const loadDepartments = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      name: searchForm.name,
      code: searchForm.code
    }
    
    const response = await queryDeptPage(params)
    if (response && response.code === '00000') {
      departmentList.value = response.data.records
      pagination.total = response.data.total
    } else {
      message.error('获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    message.error('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

const showAddModal = () => {
  isEditing.value = false
  resetForm()
  modalVisible.value = true
}

const editDepartment = (record) => {
  isEditing.value = true
  Object.assign(departmentForm, {
    ...record,
    remarkInfo: {
      applyReason: record.remarkInfo?.applyReason || '',
      auditReason: record.remarkInfo?.auditReason || '',
      applicant: record.remarkInfo?.applicant || '',
      auditor: record.remarkInfo?.auditor || '',
      applyTime: record.remarkInfo?.applyTime || '',
      auditTime: record.remarkInfo?.auditTime || '',
      history: record.remarkInfo?.history || []
    }
  })
  modalVisible.value = true
}

const deleteDepartment = async (id) => {
  try {
    const response = await deleteDept({ id })
    if (response && response.code === '00000') {
      message.success('删除部门成功')
      await loadDepartments()
    } else {
      message.error('删除部门失败')
    }
  } catch (error) {
    console.error('删除部门失败:', error)
    message.error('删除部门失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    // 准备提交数据
    const params = {
      ...departmentForm,
      remarkInfo: departmentForm.remarkInfo
    }

    let response
    if (isEditing.value) {
      // 编辑部门
      response = await updateDept(params)
    } else {
      // 添加部门
      response = await addDept(params)
    }

    if (response && response.code === '00000') {
      message.success(isEditing.value ? '更新部门成功' : '添加部门成功')
      modalVisible.value = false
      await loadDepartments()
    } else {
      message.error(isEditing.value ? '更新部门失败' : '添加部门失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(departmentForm, {
    id: undefined,
    name: '',
    code: '',
    contactPhone: '',
    address: '',
    businessLicense: '',
    status: 0,
    remarkInfo: {
      applyReason: '',
      auditReason: '',
      applicant: '',
      auditor: '',
      applyTime: '',
      auditTime: '',
      history: []
    }
  })
  isEditing.value = false
}

const handleSearch = () => {
  pagination.current = 1
  loadDepartments()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.code = ''
  pagination.current = 1
  loadDepartments()
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadDepartments()
}

// 生命周期
onMounted(async () => {
  await loadDepartments()
})
</script>

<style scoped>
.department-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.search-section {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.department-table {
  background: #fff;
  border-radius: 8px;
}
</style>